/**************************************************************************************** Import */
import _ from 'lodash';
import React, {Component} from 'react';
import { View, TextInput, Text, ScrollView, ListView } from 'react-native';
import ScrollableTabView, { ScrollableTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view';
import { Progress, Modal } from 'antd-mobile-rn';
import { Icon } from 'react-native-elements';
import { SwipeRow, List, ListItem } from 'native-base';
import Picker from 'react-native-picker';
import { CAround, CBetween, CCenter, CColumn, CFloat, CHand, CItemX, CItemY, CLine, CLoad, CRow, CWrap, CBone, CIcon, CImage, CSvg, CText, CFull, CScroll, CFooter, CHeader, CPage, CButton, CLabel, PTabbar, PHeader, PDatePicker, PCustumTabBar } from '../../library/comp';
import { Dialog, Http, PageBase } from '../../library/func';
import Design from '../../design';
import Config from '../../config';

//code push
import codePush from 'react-native-code-push';
//极光推送
import JPushModule from 'jpush-react-native'

import SplashScreen from 'react-native-splash-screen';

/**************************************************************************************** Pageload */

/**************************************************************************************** Cacheload */

/**************************************************************************************** Preload */

/**************************************************************************************** Get */

/**************************************************************************************** Post */

/**************************************************************************************** Page */
export default class ServiceVisitor extends PageBase {
	constructor(props) {
        super(props);
        this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
		this.state = {
            showModal:false,
            percent:0,
            // 页面初始请求数据
            data:{
                data:{
                    will:[],
                    already:[]
                }
            },
			untreated:[
                {
                    id:0,
                    name:'赵某',
                    phoneNumber:'15130305503',
                    goods:'空调',
                    address:'地址',
                    arrivalTime:'1545380000',
                    created:'1545379356',
                },
                {
                    id:1,
                    name:'钱某',
                    phoneNumber:'15130305503',
                    goods:'空调',
                    address:'地址',
                    arrivalTime:'1545380000',
                    created:'1545379356',
                },
                {
                    id:2,
                    name:'孙某',
                    phoneNumber:'15130305503',
                    goods:'空调',
                    address:'地址',
                    arrivalTime:'1545380000',
                    created:'1545379356',
                }
            ],
            processed:[
                {
                    id:0,
                    name:'张某',
                    phoneNumber:'15130305503',
                    goods:'洗衣机',
                    address:'地址',
                    arrivalTime:'1545383600',
                    created:'1545379356',
                }
            ],
            ago:[
                {
                    id:0,
                    name:'陈某',
                    phoneNumber:'15130305503',
                    address:'台湾',
                    arrivalTime:'1545383600',
                    created:'1545379356',
                },
                {
                    id:1,
                    name:'张某',
                    phoneNumber:'15130305503',
                    address:'湖南长沙',
                    arrivalTime:'1545383600',
                    created:'1545379356',
                },
            ],
			// 当前时间戳
			now:Date.parse(new Date())/1000,
            // 时间选择
            seleteDate:'今天',
            today:true
            
        }
        codePush.sync({
            updateDialog: {
                mandatoryContinueButtonLabel:'更新',
                mandatoryUpdateMessage:'有新版本了，请您及时更新',
                optionalIgnoreButtonLabel: '稍后',
                optionalInstallButtonLabel: '后台更新',
                optionalUpdateMessage: '有新版本了，是否更新？',
                title: '更新提示'
            },
            installMode: codePush.InstallMode.IMMEDIATE 
        },
        (status) => {
            switch (status) {
                case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                    // 显示进度条弹框
                    this.setState({
                        showModal: true
                    })
                    break;
                case codePush.SyncStatus.INSTALLING_UPDATE:
                    // 隐藏进度条弹框
                    this.setState({
                        showModal: false
                    })
                    break;
            }
        },
        ({ receivedBytes, totalBytes, }) => {

            if(receivedBytes == totalBytes){
                this.setState({
                    showModal: false
                })
            }

            this.setState({
                percent:receivedBytes/totalBytes*100,
            });
            /* 更新进度条参数 */
        }        
        );

        //极光推送
        JPushModule.initPush();
        JPushModule.notifyJSDidLoad((res) => {});
	}
	
	/************************************************************************************ Life */
    /**
     * didMount
     */
    componentDidMount(){
		setTimeout(()=>{
			SplashScreen.hide();
		},2000);
        // SplashScreen.hide();
        this.getData();
        JPushModule.addReceiveOpenNotificationListener((map) => {
            // Dialog.text(JSON.stringify(map), 1);
            // console.log(map);
        })
	}
    // https://restful.sgboke.com/he_wuliu/worker/page/express/list.php?gettime=1545448072
	/************************************************************************************ Func */
	// getData
	getData = (time,seleteDate,bool) => {
        let data = {};
        time && (data.gettime = time);

        seleteDate || (seleteDate = '今天');
        bool == '' || (bool = true)
		Http.get({
            url:"page/express/list.php",
            data:data,
            success:(data) => {
				console.log('page/express/list.php',data)
                this.setState({
                    data:data,
                    seleteDate:seleteDate,
                    today:bool
                })
            },
            pipe: Config.pipe.action.default
        })
    }
    
    // 时间选择回调函数
    changeToday = value => {
        let date = value.split('-');
        let now = this.toDate(this.state.now).substring(0,10);
        let timeStamp = '';
        now = now.split('.')
        console.log('nowwwwwwwwwwwwwww',now)
        console.log('dateeeeeeeeeeeeee',date)
        date[0] == now[0]&&
        date[1] == now[1]&&
        date[2] == now[2]?
        this.getData()
        :
        (
            timeStamp = Date.parse(new Date(value.replace(/\-/g,'/')))/1000,
            console.log('timeStampppppppppppppppppppppp',timeStamp),
            this.getData(timeStamp,value,false)

            // date = value,
            // this.setState({
            //     seleteDate:date,
            //     today:false
            // })
        )
    }

    // 隐藏一行
    deleteWillRow(secId, rowId, rowMap) {
        rowMap[`${secId}${rowId}`].props.closeRow();
        const newData = [...this.state.data.data.will];
        newData.splice(rowId, 1);
        this.state.data.data.will = newData;
        this.setState({  });
    }
    deleteAlreadyRow(secId, rowId, rowMap) {
        rowMap[`${secId}${rowId}`].props.closeRow();
        const newData = [...this.state.data.data.already];
        newData.splice(rowId, 1);
        this.state.data.data.already = newData;
        this.setState({  });
    }
	

	// 时间戳转日期
    toDate(dateStamp){
        let now = new Date(dateStamp*1000);
        // 获取日期  格式 12-09
        let year = now.getFullYear();
        let month = now.getMonth()+1;
        let day = now.getDate();
        // 月份日期补0
        month <10 && (month = '0'+month)
        day <10 && (day = '0'+day)
        let Sdate = year + '.' + month + '.' + day+'  '+ now.toTimeString().substr(0,5);
        // 返回时间  格式 08:00
        return Sdate;
    }
    // 时间戳转日期
    toTime(dateStamp){
        // 获取时间 
        let now = new Date().getTime() / 1000;
        // let arrival = new Date(dateStamp*1000);
        // 计算时间
        let time = dateStamp - now;
        let ms = parseInt(time);
        let H = parseInt(ms / 3600);
        let M = parseInt(ms % 3600 / 60);
        let S = parseInt(ms % 3600 % 60);
        // 时间补0
        H <10 && (H = '0'+H)
        M <10 && (M = '0'+M)
        S <10 && (S = '0'+S)

        console.log('time::::::',time)
        console.log('now::::::',now)
        console.log('dateStamp::::::',dateStamp)
        // let Sdate = 'now::' + now + '//////////////////dateStamp::' + dateStamp;
        // 返回时间  格式 08:00
        let Sdate = H +':' + M + ':' + S;
        return Sdate;
    }
	

	/************************************************************************************ Render */
	render() {

        const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

		return (
			<CPage bg='#efeff4'>


                {
                    this.state.today ? (
                
				<CFull f='1' bg='#efeff4' mt='98'>
					<ScrollableTabView
						tabBarActiveTextColor='#26c75e'
						style={{justifyContent:'center',backgroundColor:'#efeff4'}}
						tabBarUnderlineStyle={{backgroundColor:'#26c75e',width:'13%',left:'18.5%',height:2}}
                        locked={true} //只能通过点击tab来切换视图
						initialPage={0}
    					renderTabBar={(e) => <PCustumTabBar style={{height:45,borderBottomColor:'transparent',borderBottomWidth:0,backgroundColor:'#fff',paddingTop:25}} ></PCustumTabBar>}
					>

						{/* 未处理 */}
						<CColumn tabLabel='未处理' res style={{width:Config.map.screen.width}} >
							<ScrollView
								style={{flex:1,width:'100%',paddingBottom:30}}
                                automaticallyAdjustContentInsets={false} // 兼容性：去掉IOS头部莫名其妙的空白
							>
                                <CItemY py='20' mb='30' bg='#fff8' x='center' style={{width:'100%'}}>
                                    <CText color='#999' size='22' mb='5' style={{textAlign:'center'}}>{this.state.seleteDate}</CText>
                                    <CText color='#999' size='22' style={{textAlign:'center'}}>共计：{this.state.data.count_all}，未处理：{this.state.data.count_will}，已处理：{this.state.data.count_already}</CText>
                                </CItemY>

                                <List
                                    disableRightSwipe={true}
                                    rightOpenValue={-75}
                                    closeOnRowBeginSwipe={true}
                                    dataSource={this.ds.cloneWithRows(this.state.data.data.will)}
                                    renderRow ={ data => 
                                        <ListItem style={{borderBottomColor:'#efeff4',borderBottomWidth:1}}>
                                            <CItemY bg="#fff" mb="20">
                                                <CBetween py='10' px="40">
                                                    <CLine>
                                                        <CText size='26' color='#333'>{data.name}</CText>
                                                    </CLine>
                                                    <CText size='26' color='#999'>{data.phone}</CText>
                                                </CBetween>
        
                                                <CLine py='10' px="40" y='top'>
                                                    <CText size='24' color='#333'>地址：</CText>
                                                    <CText size='24' f="1" color="#666">{data.address}</CText>
                                                </CLine>
                                                
                                                {
                                                    data.goods &&
                                                    <CLine py='10' px="40" y='top'>
                                                        <CText size='24' color='#333'>所寄物品：</CText>
                                                        <CText size='24' f="1" color="#666">{data.goods}</CText>
                                                    </CLine>
                                                }

                                                <CLine py='10' px="40" y='top'>
                                                    <CText size='24' color='#333'>上门时间：</CText>
                                                    <CText size='24' f="1" color="#666">{this.toDate(data.gettime)}</CText>
                                                </CLine>
        
                                                <CBetween w="750" px='40'>
                                                    <CHand x="left">
                                                        {/* <CText size='24' color="#999">{this.toDate(data.created)}</CText> */}
                                                    </CHand>
                                                    
                                                    {
                                                        data.gettime >= this.state.now ?
                                                        <CItemX x="right" y='center'>
                                                            <CText size='24' color="#d81e06">距上门时间剩  {this.toTime(data.gettime)}</CText>
                                                        </CItemX>
                                                        :
                                                        <CItemX x="right" y='center'>
                                                            <CText size='24' color="#d81e06">过期未处理，请核对</CText>
                                                        </CItemX>
                                                    }
                                                </CBetween>
                                            </CItemY>
                                        </ListItem>
                                    }
                                    renderRightHiddenRow = { (data, secId, rowId, rowMap) =>
                                    <CButton onPress={_ => this.deleteWillRow(secId, rowId, rowMap)} x='center' y='center' bg='#d81e06' style={{height:'100%'}}>
                                        <CText color='#fff' size='24'>标为已处理</CText>
                                    </CButton>
                                    }
                                />
                                            
							</ScrollView>
						</CColumn>

						{/* 已处理 */}
						<CColumn tabLabel='已处理' res style={{width:Config.map.screen.width}} >
							<ScrollView
								style={{flex:1,width:'100%',paddingBottom:30}}
								automaticallyAdjustContentInsets={false} // 兼容性：去掉IOS头部莫名其妙的空白
							>
								<CItemY py='20' mb='30' bg='#fff8' x='center' style={{width:'100%'}}>
                                    <CText color='#999' size='22' mb='5' style={{textAlign:'center'}}>{this.state.seleteDate}</CText>
                                    <CText color='#999' size='22' style={{textAlign:'center'}}>共计：{this.state.data.count_all}，未处理：{this.state.data.count_will}，已处理：{this.state.data.count_already}</CText>
                                </CItemY>
                                {/* 已处理 */}
								<List
                                    disableRightSwipe={true}
                                    rightOpenValue={-75}
                                    closeOnRowBeginSwipe={true}
                                    dataSource={this.ds.cloneWithRows(this.state.data.data.already)}
                                    renderRow ={ data => 
                                        <ListItem style={{borderBottomColor:'#efeff4',borderBottomWidth:1}}>
                                            <CItemY bg="#fff" mb="20" w='750'>
                                                <CBetween py='10' px="40">
                                                    <CLine>
                                                        <CText size='26' color='#333'>{data.name}</CText>
                                                    </CLine>
                                                    <CText size='26' color='#999'>{data.phone}</CText>
                                                </CBetween>
        
                                                <CLine py='10' px="40" y='top'>
                                                    <CText size='24' color='#333'>地址：</CText>
                                                    <CText size='24' f="1" color="#666">{data.address}</CText>
                                                </CLine>
                                                
                                                {
                                                    data.goods &&
                                                    <CLine py='10' px="40" y='top'>
                                                        <CText size='24' color='#333'>所寄物品：</CText>
                                                        <CText size='24' f="1" color="#666">{data.goods}</CText>
                                                    </CLine>
                                                }

                                                <CLine py='10' px="40" y='top'>
                                                    <CText size='24' color='#333'>上门时间：</CText>
                                                    <CText size='24' f="1" color="#666">{this.toDate(data.gettime)}</CText>
                                                </CLine>
        
                                            </CItemY>
                                        </ListItem>
                                    }
                                    renderRightHiddenRow = { (data, secId, rowId, rowMap) =>
                                    <CButton onPress={_ => this.deleteAlreadyRow(secId, rowId, rowMap)} x='center' y='center' bg='#eee' style={{height:'100%'}}>
                                        <CText color='#333' size='24'>标为未处理</CText>
                                    </CButton>
                                    }
                                />
                                
							</ScrollView>
						</CColumn>
						
					</ScrollableTabView>
				</CFull>
                ):(
                <CScroll bg='#efeff4' mt='98'>
                    <CItemY py='20' mb='30' bg='#fff8' x='center'>
                        <CText color='#999' size='22' mb='5' style={{textAlign:'center'}}>{this.state.seleteDate}</CText>
                        <CText color='#999' size='22' style={{textAlign:'center'}}>共计：{this.state.data.count_all}，未处理：{this.state.data.count_will}，已处理：{this.state.data.count_already}</CText>
                    </CItemY>
                    {/* 未处理 */}
                    <List
                        disableRightSwipe={true}
                        rightOpenValue={-75}
                        closeOnRowBeginSwipe={true}
                        dataSource={this.ds.cloneWithRows(this.state.data.data.will)}
                        renderRow ={ data => 
                            <ListItem style={{borderBottomColor:'#efeff4',borderBottomWidth:1}}>
                                <CItemY bg="#fff" mb="20">
                                    <CBetween py='10' px="40">
                                        <CLine>
                                            <CText size='26' color='#333'>{data.name}</CText>
                                        </CLine>
                                        <CText size='26' color='#999'>{data.phone}</CText>
                                    </CBetween>

                                    <CLine py='10' px="40" y='top'>
                                        <CText size='24' color='#333'>地址：</CText>
                                        <CText size='24' f="1" color="#666">{data.address}</CText>
                                    </CLine>
                                    
                                    {
                                        data.goods &&
                                        <CLine py='10' px="40" y='top'>
                                            <CText size='24' color='#333'>所寄物品：</CText>
                                            <CText size='24' f="1" color="#666">{data.goods}</CText>
                                        </CLine>
                                    }

                                    <CLine py='10' px="40" y='top'>
                                        <CText size='24' color='#333'>上门时间：</CText>
                                        <CText size='24' f="1" color="#666">{this.toDate(data.gettime)}</CText>
                                    </CLine>

                                    <CBetween w="750" px='40'>
                                        <CHand x="left">
                                            {/* <CText size='24' color="#999">{this.toDate(data.created)}</CText> */}
                                        </CHand>
                                        
                                        {
                                            data.arrivalTime >= this.state.now ?
                                            <CItemX x="right" y='center'>
                                                <CText size='24' color="#d81e06">距上门时间剩  {this.toTime(data.gettime)}</CText>
                                            </CItemX>
                                            :
                                            <CItemX x="right" y='center'>
                                                <CText size='24' color="#d81e06">过期未处理，请核对</CText>
                                            </CItemX>
                                        }
                                    </CBetween>
                                </CItemY>
                            </ListItem>
                        }
                        renderRightHiddenRow = { (data, secId, rowId, rowMap) =>
                        <CButton onPress={_ => this.deleteWillRow(secId, rowId, rowMap)} x='center' y='center' bg='#d81e06' style={{height:'100%'}}>
                            <CText color='#fff' size='24'>标为已处理</CText>
                        </CButton>
                        }
                    />
                    {/* 已处理 */}
                    <List
                        disableRightSwipe={true}
                        disableLeftSwipe={true}
                        rightOpenValue={-75}
                        closeOnRowBeginSwipe={true}
                        dataSource={this.ds.cloneWithRows(this.state.data.data.already)}
                        renderRow ={ data => 
                            <ListItem style={{borderBottomColor:'#efeff4',borderBottomWidth:1}}>
                                <CItemY bg="#fff" mb="20" w='750'>
                                    <CBetween py='10' px="40">
                                        <CLine>
                                            <CText size='26' color='#333'>{data.name}</CText>
                                        </CLine>
                                        <CText size='26' color='#999'>{data.phone}</CText>
                                    </CBetween>

                                    <CLine py='10' px="40" y='top'>
                                        <CText size='24' color='#333'>地址：</CText>
                                        <CText size='24' f="1" color="#666">{data.address}</CText>
                                    </CLine>
                                    
                                    {
                                        data.goods &&
                                        <CLine py='10' px="40" y='top'>
                                            <CText size='24' color='#333'>所寄物品：</CText>
                                            <CText size='24' f="1" color="#666">{data.goods}</CText>
                                        </CLine>
                                    }

                                    <CLine py='10' px="40" y='top'>
                                        <CText size='24' color='#333'>上门时间：</CText>
                                        <CText size='24' f="1" color="#666">{this.toDate(data.gettime)}</CText>
                                    </CLine>

                                </CItemY>
                            </ListItem>
                        }
                        renderRightHiddenRow = { (data, secId, rowId, rowMap) =>
                        <CButton onPress={_ => this.deleteAlreadyRow(secId, rowId, rowMap)} x='center' y='center' bg='#d81e06' style={{height:'100%'}}>
                            <CText color='#fff' size='24'>标为已处理</CText>
                        </CButton>
                        }
                    />
                </CScroll>
                )}

				{/* PHeader */}
                <PHeader nav={this.nav} style={{borderBottomColor:'#efeff4',borderBottomWidth:1}}
                    right={
                        <PDatePicker type='date' cback={(value)=>this.changeToday(value)}>
                            <Icon name='date-range' />
                        </PDatePicker>
                    }
                >物流快递</PHeader>

                {/* 进度条弹框 */}
                <Modal
                    style={{width:300,height:70}}
                    popup={true}
                    transparent={true}
                    visible={this.state.showModal}
                    animationType="slide-up"
                >
                    <CText mb='22' style={{marginTop:-3}}>进度：{this.state.Progress}</CText>
                    <Progress percent={this.state.percent} position='normal' unfilled={true} style={{backgroundColor:'#eee'}} barStyle={{backgroundColor:'#59aaff'}}> </Progress>
                    {/* <CButton mt='30' bg='#1296db' color='#fff' size='24' ra='6' py='10' onPress={()=>{this.setState({ showModal:false });clearInterval(this.timer)}}>后台更新</CButton> */}
                </Modal>
			</CPage>
		);
	}
}
